package com.linkhub.oms.admin.modules.satoken.log;

import com.dtflys.forest.logging.DefaultLogHandler;
import com.dtflys.forest.logging.RequestLogMessage;
import com.dtflys.forest.logging.ResponseLogMessage;
import com.dtflys.forest.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: LogbackHandler
 * @Author: echo
 * @Date: 2024/4/8 21:16
 * @Version: 1.0
 */
@Slf4j
public class LogbackHandler extends DefaultLogHandler {

    @Override
    public void logContent(String content) {
        log.info(content);
    }

    @Override
    protected String requestLoggingContent(RequestLogMessage requestLogMessage) {
        final StringBuilder builder = new StringBuilder();
        builder.append("Request ");
        builder.append(asyncModeContent(requestLogMessage));
        builder.append(backendContent(requestLogMessage));
        builder.append(retryContent(requestLogMessage));
        builder.append(redirection(requestLogMessage));
        builder.append(proxyContent(requestLogMessage));
        builder.append(requestTypeChangeHistory(requestLogMessage));
        builder.append(requestLogMessage.getRequestLine());
        builder.append("; ");
        final String headers = requestLoggingHeaders(requestLogMessage);
        if (StringUtils.isNotEmpty(headers)) {
            builder.append("; Headers: ");
            builder.append(headers);
        }
        final String body = requestLoggingBody(requestLogMessage);
        if (StringUtils.isNotEmpty(body)) {
            builder.append("; Body: ");
            builder.append(body);
        }
        return builder.toString();
    }

    @Override
    public void logResponseContent(ResponseLogMessage responseLogMessage) {
        if (responseLogMessage.getResponse() != null) {
            final String content = responseLogMessage.getResponse().getContent();
            if (StringUtils.isNotEmpty(content)) {
                logContent("Response Content: " + content);
            }
        }
    }
}
